from sqlalchemy import (
    Column, String, ForeignKey, DateTime
)
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import UUID

import uuid
from datetime import datetime
import secrets
import string

from app.db import Database

class Login(Database.Base):
    __tablename__ = 'login'

    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, unique=True, nullable=False)
    token = Column(String, unique=True, nullable=False)
    last_ip = Column(String)
    user_id = Column(UUID(as_uuid=True), ForeignKey("users.id"))
    user_agent = Column(String)
    access_at = Column(DateTime, default=datetime.now)
    created_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

    user = relationship('User')

    def __init__(self, user_id, last_ip, user_agent):
        self.user_id = user_id
        self.last_ip = last_ip
        self.user_agent = user_agent
        self.token = self.generate_token()

    @staticmethod
    def generate_token():
        alphabet = string.ascii_letters + string.digits
        token = ''.join(secrets.choice(alphabet) for _ in range(36))
        return token

Database.create_table_all()
